package com.village.friend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.village.friend.constant.ChatWords;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.dto.request.*;
import com.village.friend.dto.response.*;
import com.village.friend.entity.Activity;
import com.village.friend.entity.User;
import com.village.friend.entity.UserLike;
import com.village.friend.entity.UserWechatLook;
import com.village.friend.redis.RedisService;
import com.village.friend.service.*;
import com.village.friend.service.impl.UserLikeServiceImpl;
import com.village.friend.utils.ParamUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/home")
@Api(tags = "首页")
public class HomeController {

    @Autowired
    private UserLookService userLookService;
    @Autowired
    private UserLikeServiceImpl userLikeService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserWechatLookService userWechatLookService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    RedisService redisService;
    @Autowired
    OpenImService openImService;

    @ApiOperation(value = "首页")
    @GetMapping(value = "/list")
    public BaseResponse<IPage<HomeListUserResDto>> list(ListDto param) {
        String salaryYear = param.getSalaryYear();
        if ("全部".equals(salaryYear)) {
            param.setSalaryYear(null);
        }
        Integer sortMode = param.getSortMode();
        if (sortMode != null) {
            param.setMode(sortMode);
        }
        String city = param.getCity();
        if (StringUtils.isNotBlank(city)) {
            if (city.equals("襄樊")) {
                param.setCity("襄阳");
            }
        }
        User userRedis = redisService.getUser(param.getToken());
        // 查询用户信息
        IPage<HomeListUserResDto> pageData = new Page<>(param.getPage(), param.getLimit());
        Integer limit = param.getLimit();
        Integer offset = (param.getPage() - 1) * limit;
        Integer gender = userRedis.getGender();
        Integer tarGender = 0;
        if (gender == 0) {
            tarGender = 1;
        }
        List<User> list = userService.list(userRedis.getUid(), tarGender, param.getCity(), param.getAgeStart(), param.getAgeEnd(), param.getHeightStart(), param.getHeightEnd(), param.getSalaryYear(), userRedis.getLatitude(), userRedis.getLongitude(), offset, limit, param.getMode());
        List<HomeListUserResDto> dataList = new ArrayList<>();
        for (User userEntity : list) {
            HomeListUserResDto data = ParamUtils.userToHomeListUserResDto(userEntity);
            dataList.add(data);
        }
        Integer total = userService.listCount(userRedis.getUid(), tarGender, param.getCity(), param.getAgeStart(), param.getAgeEnd(), param.getHeightStart(), param.getHeightEnd(), param.getSalaryYear());
        pageData.setTotal(total);
        pageData.setRecords(dataList);
        return new BaseResponse(MsgCodeEnum.SUCCESS, pageData);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/homeUser")
    public BaseResponse<HomeUserResDto> getUser(HomeGetUserDto param) {
        if (param.getUserIdLooked() == 1 || param.getUserIdLooked() == 2) {
            return new BaseResponse(MsgCodeEnum.MANAGER_ERROR, null);
        }
        User userRedis = redisService.getUser(param.getToken());
        String lookedKey = "looked_" + userRedis.getUid() + "_" + param.getUserIdLooked();
        String s = redisService.get(lookedKey);
        //   openImService.sendMsgByManagerLook(param.getUserIdLooked(), userRedis.getName() + ChatWords.USER_LOOKED);
        if (StringUtils.isEmpty(s)) {
            openImService.sendMsgByManagerLook(param.getUserIdLooked(), userRedis.getName() + ChatWords.USER_LOOKED);
        }
        // 查询用户基本信息
        User user = userService.getUserByUserId(param.getUserIdLooked(), userRedis.getLongitude(), userRedis.getLatitude());
        HomeUserResDto userMsg = ParamUtils.userToHomeUserResDto(user);
        if (userRedis.getGender() == user.getGender()) {
            return new BaseResponse(MsgCodeEnum.SAME_GENDER_ERROR, null);
        }
        // 记录查询历史
        userLookService.insertOrUpdate(userRedis.getUid(), param.getUserIdLooked());
        // 是否喜欢
        QueryWrapper<UserLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userRedis.getUid());
        queryWrapper.eq("user_id_like", param.getUserIdLooked());
        UserLike userLike = userLikeService.getOne(queryWrapper);
        if (userLike == null) {
            userMsg.setIsLike(0);
        } else {
            userMsg.setIsLike(1);
        }
        // 用户活动数据
        List<Activity> list = activityService.list(param.getUserIdLooked(), null, userRedis.getUid(), null, null, null, userRedis.getLatitude(), userRedis.getLongitude(), 100, 0);
        Integer total = activityService.listCount(param.getUserIdLooked(), null, userRedis.getUid(), null, null, null);

        List<String> activityPhotos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                List<String> images = ParamUtils.jsonStrToList(list.get(i).getImages());
                if (images != null && images.size() > 0) {
                    activityPhotos.addAll(images);
                }
            }
        }
        int size = 3;
        if (activityPhotos.size() <= 3) {
            size = activityPhotos.size();
        }
        List<String> activityPhotosRZ = activityPhotos.subList(0, size);
        userMsg.setActivityCount(total);
        userMsg.setActivityPhotos(activityPhotosRZ);
        // 是否展示微信
        UserWechatLook userLook = userWechatLookService.getUserLook(userRedis.getUid(), param.getUserIdLooked());
        if (userLook == null && StringUtils.isNotBlank(userMsg.getWeChatAccount())) {
            userMsg.setIsShowWeChat(1);
            userMsg.setWeChatAccount("已隐藏");
        } else {
            userMsg.setIsShowWeChat(2);
            userMsg.setWeChatAccount(userMsg.getWeChatAccount());
            if (StringUtils.isBlank(userMsg.getWeChatAccount())) {
                userMsg.setIsShowWeChat(0);
                userMsg.setWeChatAccount("未填写");
            }
        }
        redisService.set(lookedKey, "1", 3600 * 24);
        return new BaseResponse(MsgCodeEnum.SUCCESS, userMsg);
    }

    @ApiOperation(value = "谁看过我")
    @GetMapping(value = "/listLook")
    public BaseResponse<IPage<ListUserLookResDto>> listLook(ListLookDto param) {
        User userRedis = redisService.getUser(param.getToken());
        User userEntity = userService.getUserByUserId(userRedis.getUid(), userRedis.getLongitude(), userRedis.getLatitude());

        Integer total = userLookService.getLookCount(userRedis.getUid());
        Integer limit = param.getLimit();
        Integer offset = (param.getPage() - 1) * limit;


        IPage<ListUserLookResDto> pageData = new Page<>(param.getPage(), param.getLimit());
        List<User> list = userLookService.getLookList(userRedis.getUid(), offset, limit);
        List<ListUserLookResDto> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            ListUserLookResDto data = ParamUtils.userToListUserLookResDto(user);
            dataList.add(data);
        }
        pageData.setTotal(total);

        if (userEntity.getVipLeft() <= 0 && total >= 3) {
            // 不是vip  ，请求多于2页
            if (param.getPage() >= 2) {
                pageData.setRecords(new ArrayList<>());
            } else if (param.getPage() <= 1 && dataList.size() >= 3) {
                // 不是vip  ，请求1页，多于3条
                List<ListUserLookResDto> dataListSub = dataList.subList(0, 3);
                pageData.setRecords(dataListSub);
            } else {
                // 不是vip  ，请求1页 ，少于3条
                pageData.setRecords(dataList);
            }
        } else {
            //  vip
            pageData.setRecords(dataList);
        }


        return new BaseResponse(MsgCodeEnum.SUCCESS, pageData);
    }


    @ApiOperation(value = "查看用户微信")
    @GetMapping(value = "/weChat")
    public BaseResponse<HomeWeChatResDto> weChat(HomeWeChatDto param) {
        User userRedis = redisService.getUser(param.getToken());
        User userMsg = userService.getUserByUserId(userRedis.getUid(), userRedis.getLongitude(), userRedis.getLatitude());
        Integer vipLevel = userMsg.getVipLevel();
        Integer vipLeft = userMsg.getVipLeft();
        if (vipLevel == 0) {
            //  不是vip
            return new BaseResponse(MsgCodeEnum.WECHAT_NO_VIP, null);
        }
        if (vipLeft == null || vipLeft <= 0) {
            // vip 已过期

        }
        // 当日微信号查看次数已用完
        Integer todayUserLookCount = userWechatLookService.getTodayUserLookCount(userRedis.getUid());
        if (todayUserLookCount >= 10) {
            return new BaseResponse(MsgCodeEnum.WECHAT_COUNT_END, null);
        }
        userWechatLookService.insertOrUpdate(userRedis.getUid(), param.getUserIdLooked());

        // 查询 用户微信
        User user = userService.getUserByUserId(param.getUserIdLooked(), userRedis.getLongitude(), userRedis.getLatitude());
        HomeWeChatResDto HomeWeChatResDto = new HomeWeChatResDto();
        HomeWeChatResDto.setWeChat(user.getWeChatAccount());
        return new BaseResponse(MsgCodeEnum.SUCCESS, HomeWeChatResDto);
    }

    @ApiOperation(value = "token验证:主要是给图片服务做验证")
    @GetMapping(value = "/tokenCheck")
    public BaseResponse<String> tokenCheck(BaseRequestDto param) {
        User userRedis = redisService.getUser(param.getToken());
        if (userRedis == null || userRedis.getUid() == null) {
            return new BaseResponse(MsgCodeEnum.AUTH_ERROR, null);
        } else {
            return new BaseResponse(MsgCodeEnum.SUCCESS, null);
        }
    }

    @ApiOperation(value = "ping")
    @GetMapping(value = "/ping")
    public BaseResponse<String> ping() {
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }
}
